<template>
  <div>
    <el-row class="picture_search">
      <el-form
        :inline="true"
        :model="queryData.searchData"
        label-width="100px"
        class="demo-form-inline"
        size="small"
        label-suffix="："
      >
        <el-form-item label="图片ID">
          <el-input v-model="queryData.searchData.id" placeholder="请输入图片ID" style="width:200px;"></el-input>
        </el-form-item>
        <el-form-item label="图片名称">
          <el-input
            v-model="queryData.searchData.image_name"
            placeholder="请输入图片标题"
            style="width:200px;"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="关键字">
          <el-input
            v-model="queryData.searchData.queryWords"
            placeholder="关键字"
            style="width:200px;"
          ></el-input> 
        </el-form-item>-->
        <el-form-item label="图片作者">
          <el-input
            v-model="queryData.searchData.img_designer"
            placeholder="请输入图片作者"
            style="width:200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片标签">
          <el-autocomplete
            clearable
            @clear="clearSelectedTag"
            style="width:200px;"
            v-model="selectTag"
            :fetch-suggestions="queryTags"
            placeholder="请输入id或名称"
            @select="((item)=>{handleSelectTag(item)})"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="图片分类">
          <el-autocomplete
            clearable
            @clear="clearSelectedCategory"
            style="width:200px;"
            v-model="selectCategory"
            :fetch-suggestions="queryCategory"
            placeholder="分类id或名称"
            @select="handleSelectCategory"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="图片状态">
          <el-select
            v-model="queryData.searchData.status"
            placeholder="请选择图片状态"
            style="width:200px;"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            style="width:200px;"
            v-model="queryData.searchData.create_time"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-button icon="el-icon-search" @click="onSubmit" size="small">搜索</el-button>
        <el-button icon="el-icon-brush" @click="resetFrom" size="small">重置</el-button>
      </el-form>
    </el-row>
    <el-row style="margin-bottom:16px;">
      <el-dropdown
        trigger="click"
        @command="bsatchOperation"
        type="default"
        split-button
        style="margin-right:10px;"
      >
        图片批量管理
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-top" command="shelves">批量上架</el-dropdown-item>
          <el-dropdown-item icon="el-icon-bottom" command="delisted">批量下架</el-dropdown-item>
          <el-dropdown-item icon="el-icon-s-grid" command="editCategory">批量修改分类</el-dropdown-item>
          <el-dropdown-item icon="el-icon-s-grid" command="getImageIds">批量导出图片ID</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dialog title="批量修改分类" :visible.sync="categoryBatchForm">
        <el-form :model="batchCategoryForm">
          <el-form-item label="分类列表" label-width="120px">
            <el-cascader :options="categoryOptions" v-model="batchCategoryForm.id"></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="categoryBatchForm = false">取 消</el-button>
          <el-button type="primary" @click="editBatchCategory">确 定</el-button>
        </div>
      </el-dialog>

      <el-button @click="TagsInBatches" style="margin-right:10px;">批量增加/删除标签</el-button>
      <el-dialog title="批量添加/删除标签" :visible.sync="dialogFormVisible" :before-close="closeDialog">
        <label>您选中的图片包含以下标签：</label>
        <div style="width:100%;border:1px solid #ddd;border-radius:3px;padding:5px;">
          <el-tag
            closable
            v-for="(item,index) in newLabels"
            :key="index"
            @close="deleteTagInIds(item.id,index)"
          >{{item.name}}</el-tag>
        </div>
        <el-select
          v-model="newTags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择标签"
          style="width:100%;"
        >
          <el-option
            v-for="item in unique(tagList)"
            :key="item.index"
            :label="item.name"
            :value="item"
          ></el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddTags">取 消</el-button>
          <el-button type="primary" icon="el-icon-top" @click="addTags()">添加</el-button>
        </div>
      </el-dialog>
      <el-dropdown
        trigger="click"
        @command="addToTopic"
        type="default"
        split-button
        style="margin-right:10px;"
      >
        添加到【专题】
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="item in imageTopicList"
            :key="item.id"
            :command="item"
          >{{item.position===1?'首页推荐':'设计新秀'}}-{{item.name}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown trigger="click" type="default" split-button style="margin-right:10px;">
        表格列控制
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <label>
              <el-switch
                v-model="isLoadPicture"
                active-color="#13ce66"
                inactive-color
                style="margin-right:5px"
              ></el-switch>显示图片
            </label>
          </el-dropdown-item>
          <el-dropdown-item>
            <label>
              <el-switch
                v-model="isLoadImgDesigner"
                active-color="#13ce66"
                inactive-color
                style="margin-right:5px"
              ></el-switch>显示作者
            </label>
          </el-dropdown-item>
          <el-dropdown-item>
            <label>
              <el-switch
                v-model="isLoadCategory"
                active-color="#13ce66"
                inactive-color
                style="margin-right:5px"
              ></el-switch>显示分类
            </label>
          </el-dropdown-item>
          <el-dropdown-item>
            <label>
              <el-switch
                v-model="isLoadOthers"
                active-color="#13ce66"
                inactive-color
                style="margin-right:5px"
              ></el-switch>显示其他
            </label>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button @click="downloadForm" icon="el-icon-download">导出CSV文档</el-button>
      <el-popover ref="popover5" trigger="click" placement="bottom" width="200" v-model="popover">
        <el-input type="textarea" disabled="disabled" v-model="imageIdList"></el-input>
        <div style="text-align: right; margin: 0">
          <el-button type="primary" size="mini" v-clipboard:copy="imageIdList" @click="popover=false">复制</el-button>
        </div>
      </el-popover>
      <el-button style="margin-left:10px;"  v-popover:popover5>复制图片ID</el-button>
    </el-row>
    <el-row>
      <el-table
        border
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        id="out-table"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
        <el-table-column prop="img_name" label="名称" header-align="center"></el-table-column>
        <el-table-column prop="describe" label="描述" header-align="center"></el-table-column>
        <el-table-column prop="tags" label="标签" header-align="center" min-width="260">
          <template slot-scope="scope">
            <el-tag
              closable
              v-for="(item, index) in scope.row.label"
              :key="index"
              @close="handleClose(scope.row.id,item.id)"
              size="mini"
              style="margin-right:5px;"
            >{{ item.name }}</el-tag>
            <el-button
              icon="el-icon-plus"
              size="mini"
              type="text"
              circle
              @click="visible = true,open_add_tag(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="isLoadCategory" prop="category" label="分类" width="80"></el-table-column>
        <el-table-column
          :key="Math.random()"
          prop="size"
          label="尺寸"
          v-if="isLoadOthers"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <div v-for="(item,i) in scope.row.size.split(',')" :key="i" style="text-align:left;">
              {{item}}
              <br v-if="i!==4" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          align="center"
          v-if="isLoadImgDesigner"
          prop="img_designer"
          label="图片作者"
          show-overflow-tooltip
        ></el-table-column>

        <el-table-column
          :key="Math.random()"
          prop="create_time"
          label="上传时间"
          show-overflow-tooltip
          v-if="isLoadOthers"
          align="center"
        >
          <template slot-scope="scope">
            <p>{{parseInt(scope.row.create_time)|timestampToDate}}</p>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isLoadPicture"
          min-width="120"
          prop="img_thumbnail"
          label="缩略图"
          align="center"
        >
          <template slot-scope="scope">
            <el-popover placement="right" trigger="click">
              <el-image :src="scope.row.img_thumbnail|fillImgShot" fit="contain"></el-image>
              <el-button slot="reference" style="padding:0;margin:0;border-radio:0;border:none;">
                <el-image
                  :src="scope.row.img_thumbnail | fillImgShot"
                  fit="cover"
                  style="width:150px;height:100px;border:none;"
                ></el-image>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="watch_num"
          label="浏览量"
          align="center"
          show-overflow-tooltip
          v-if="isLoadOthers"
          width="80"
        ></el-table-column>
        <el-table-column
          width="80"
          align="center"
          prop="download_counts"
          label="下载量"
          show-overflow-tooltip
          v-if="isLoadOthers"
        ></el-table-column>
        <el-table-column
          width="80"
          align="center"
          prop="conversionRrate"
          label="转化率"
          show-overflow-tooltip
          v-if="isLoadOthers"
        >
          <template slot-scope="scope">
            <!-- {{ (Math.round( (scope.row.download_counts / scope.row.watch_num) * 100 ) / 100) | fomatFloat }} -->
            {{(scope.row.download_counts/scope.row.watch_num)|fomatFloat(2)}}
          </template>
        </el-table-column>

        <el-table-column
          prop="is_enable"
          label="上架/下架"
          width="150"
          column-key="is_enable"
          header-align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_enable_Bool"
              active-text="上架"
              inactive-text="下架"
              @change="singleOffOrUp($event, scope.row.id)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="is_enable"
          label="操作"
          width="80"
          column-key="is_enable"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editPicture(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top:15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10,30,100,200,500]"
          :page-size="queryData.pageSet.pagesize"
          :pager-count="7"
          layout="sizes, prev, pager, next,jumper, ->,total"
          :total="total"
        ></el-pagination>
      </div>
      <el-dialog title="编辑图片信息" :visible.sync="showEditPictureDialog" :close-on-click-modal="false">
        <el-form :model="editForm" :rules="rules" ref="editPicture">
          <el-form-item label="图片名称" :label-width="formLabelWidth" prop="img_name">
            <el-input v-model="editForm.img_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片来源url" :label-width="formLabelWidth" prop="url">
            <el-input v-model="editForm.url" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片作者" :label-width="formLabelWidth" prop="img_designer">
            <el-input v-model="editForm.img_designer" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="下载次数" :label-width="formLabelWidth" prop="download_counts">
            <el-input v-model="editForm.download_counts" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="查看次数" :label-width="formLabelWidth" prop="watch_num">
            <el-input v-model="editForm.watch_num" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="点赞次数" :label-width="formLabelWidth" prop="like_num">
            <el-input v-model="editForm.like_num" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片描述" :label-width="formLabelWidth">
            <el-input v-model="editForm.describe" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetEdit">取 消</el-button>
          <el-button
            type="primary"
            :loading="button_loading"
            @click="updatePicture('editPicture')"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-row>
    <el-dialog
      :title="'当前图片id:'+row.id"
      :visible.sync="visible"
      width="30%"
      :append-to-body="true"
      :before-close="handleCloseAddTag"
    >
      <el-autocomplete
        class="inline-input"
        clearable
        @clear="clearNewLabel"
        style="width:100%;"
        v-model="newLabel"
        :fetch-suggestions="querySearch"
        placeholder="请输入标签id或名称"
        @select="((item)=>{handleSelect(item)})"
      ></el-autocomplete>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="addTag(row.id,row.label)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "HeaderSearch",
  data() {
    return {
      row: { id: "", img_name: "", label: "", newTag: "" },
      button_loading: false,
      popover: false,
      rules: {
        img_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        url: [{ required: true, message: "请输入来源地址", trigger: "blur" }],
        img_designer: [
          { required: true, message: "请输入作者", trigger: "blur" }
        ],
        download_counts: [
          { required: true, message: "请输入下载次数", trigger: "blur" }
        ],
        watch_num: [
          { required: true, message: "请输入查看次数", trigger: "blur" }
        ],
        like_num: [
          { required: true, message: "请输入点赞次数", trigger: "blur" }
        ]
      },
      showEditPictureDialog: false,
      categoryBatchForm: false,
      batchCategoryForm: {
        id: []
      },
      imageIdList: "",
      categoryOptions: [],
      statusOptions: [
        {
          status: 0,
          label: "已经上架"
        },
        {
          status: 1,
          label: "已经下架"
        }
      ],
      lable: {},
      total: 0, //图片总数
      // 是否显示图片
      isLoadPicture: true,
      // 是否显示图片作者
      isLoadImgDesigner: false,
      // 是否显示图片类别
      isLoadCategory: false,
      // 是否显示其他
      isLoadOthers: true,
      value1: [],
      newLabel: "",
      // 批量添加标签
      newLabels: [],
      selectedLabels: [],
      selectedIds: [],
      dialogFormVisible: false,
      formLabelWidth: "120px",
      visible: false,
      // table 已经选中的数据
      multipleSelection: [],
      selected: [],
      // 分页
      page: 1, //默认第一页
      pageSize: 30, //每页大小默认值
      // 分类选项
      categoryData: [],
      editForm: {
        id: "",
        url: "",
        describe: "", //描述
        img_name: "", //图片标题
        img_designer: "", //图片作者
        download_counts: "", //下载次数
        watch_num: "", //查看次数
        like_num: ""
      },
      queryData: {
        searchData: {
          id: "",
          image_name: "", //图片标题
          tagId: "", //图片标签
          queryWords: "", //图片标签
          category: "", //图片类别
          img_designer: "", //图片作者
          status: "", //图片状态
          create_time: ""
        },
        pageSet: {
          page: 1,
          pagesize: 10
        }
      },
      selectCategory: "", //被选中的分类
      selectTag: "", //被选中的tag
      tableData: [],
      tagList: [],
      imageTopicList: [],
      checkAll: false,
      isIndeterminate: true,
      newTags: [],
      // 选择器选项
      pickerOptions: {
        // 还没到的日期禁用
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        // 日期快捷选项
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      }
    };
  },
  created() {
    this.getCategory();
    this.loadTags();
    this.getImageTopic();
  },
  mounted() {
    this.loaddata(this.queryData);
  },
  watch: {
    multipleSelection: function(newVal) {
      this.imageIdList=''
      var imageIds=[]
      newVal.forEach(item => {
        imageIds.push(item.id);
      });
      this.imageIdList = imageIds.toString();
    },
    
  },
  methods: {
    copyImageIds(){

    },
    open_add_tag(item) {
      this.row = item;
    },
    clearNewLabel() {
      this.newLabel = "";
    },
    resetEdit() {
      this.showEditPictureDialog = false;
      for (var key in this.editForm) {
        this.editForm[key] = "";
      }
      this.loaddata(this.queryData);
    },
    getImageTopic() {
      this.axios.post("/topic/getImgTopic", { tp_type: 3 }).then(res => {
        this.imageTopicList = res;
      });
    },
    updatePicture(formName) {
      this.button_loading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.axios
            .post("/imagebase/updatePicture", this.editForm)
            .then(res => {
              if (res[0] > 0) {
                this.showEditPictureDialog = false;
                this.resetEdit();
                this.$message.info("更新成功");
              } else {
                this.$message.info("您没有任何更改");
              }
              this.button_loading = false;
            })
            .catch(() => {
              this.$message.error("更新失败");
            });
        }
      });
    },
    //编辑图片框显示
    editPicture(params) {
      this.showEditPictureDialog = true;
      Object.assign(this.editForm, params);
    },
    singleOffOrUp(v, id) {
      if (!v) {
        this.singleOff(id);
      } else {
        this.singleUp(id);
      }
    },
    clearSelectedTag() {
      this.queryData.searchData.tagId = "";
    },
    clearSelectedCategory() {
      this.queryData.searchData.category = "";
    },

    handleSelectTag(item) {
      this.queryData.searchData.tagId = item.id;
    },
    handleSelectCategory(item) {
      this.queryData.searchData.category = item.id;
    },
    //查询分类
    queryCategory(queryString, cb) {
      this.categoryData = [];
      if (queryString != "") {
        this.axios
          .post("/category/findByIdorName", { queryString })
          .then(res => {
            if (res.length > 0) {
              res.forEach(item => {
                this.categoryData.push({
                  id: item.id,
                  value: item.name
                });
              });
            } else {
              this.categoryData.push({
                id: "-999",
                value: "无搜索结果"
              });
            }
          });
      } else {
        this.categoryData.push({
          id: "-999",
          value: "无搜索结果"
        });
      }
      cb(this.categoryData);
    },

    //查询标签
    queryTags(queryString, cb) {
      this.TagsData = [];
      if (queryString != "") {
        this.axios.post("/tag/getTagByIdOrName", { queryString }).then(res => {
          if (res.length > 0) {
            res.forEach(item => {
              this.TagsData.push({
                id: item.id,
                value: item.name
              });
            });
          } else {
            this.TagsData.push({
              id: "无搜索结果",
              value: "无搜索结果"
            });
          }
        });
      } else {
        this.TagsData.push({
          id: "无搜索结果",
          value: "无搜索结果"
        });
      }
      cb(this.TagsData);
    },

    //查询专题
    queryTopic(queryString, cb) {
      this.TopicData = [];
      if (queryString != "") {
        this.axios
          .post("/topic/getTopicByIdOrName", { queryString })
          .then(res => {
            if (res.length > 0) {
              res.forEach(item => {
                this.TopicData.push({
                  id: item.id,
                  value: item.name
                });
              });
            } else {
              this.TopicData.push({
                id: "无搜索结果",
                value: "无搜索结果"
              });
            }
          });
      } else {
        this.TopicData.push({
          id: "无搜索结果",
          value: "无搜索结果"
        });
      }
      cb(this.TopicData);
    },

    closeDialog() {
      this.newTags = []; //清空选项框
      this.dialogFormVisible = false;
      this.loaddata(this.queryData);
    },

    addToTopic(val) {
      var multipleSelection = this.multipleSelection;
      if (multipleSelection.length > 0) {
        var ids = [];
        for (const obj of multipleSelection) {
          ids.push(obj.id);
        }
        this.axios
          .post("/topic/imagesInTopic", { imageId: ids, topic: val })
          .then(res => {
            if (res.code == 200) {
              this.$message.success("成功添加到专题" + val.name);
              this.loaddata(this.queryData);
            }
          })
          .catch(() => {
            this.$message.error("添加到专题" + val.name + "失败");
          });
      } else {
        this.$message.error("请选择需要添加到专题" + val.name + "的图片");
      }
    },

    // 热门配置
    hotConfig() {
      // 调用add函数，将dataList数据传递给dialog组件
      this.add();
      this.$router.push("/hotConfig");
    },

    // 将已选传递给hotConfig组件
    add() {
      this.bus.$emit("pass_selected", this.multipleSelection);
    },

    homeSuggest() {
      this.$router.push("/suggestConfig");
    },

    // 单个图片添加标签
    addTag(img_id, tags) {
      var newTag = this.newLabel.replace(/^\s+|\s+$/g, "");
      if (newTag === "") {
        this.$message.error("标签名称不能为空！");
        return;
      }
      if (this.checkExistence(newTag)) {
        newTag = this.checkExistence(newTag);
      }
      var tag = { name: "" };
      if (typeof newTag === "string") {
        tag.name = newTag;
      } else {
        tag.name = newTag.name;
        tag.tag_id = newTag.id;
      }
      for (var i in tags) {
        if (tag.name === tags[i]["name"]) {
          this.$message.info('"' + tag.name + '"' + "已存在！");
          return;
        }
      }
      var data = { img_id, tag };
      this.axios
        .post("/tagImage/addTag", data)
        .then(res => {
          if (res.code > 0) {
            this.visible = false;
            this.newLabel = "";
            this.$message.success("添加成功");
            this.loaddata(this.queryData);
            this.loadTags();
          }
        })
        .catch(() => {
          this.$message.error("添加失败");
        });
    },

    checkExistence(str) {
      for (var obj of this.tagList) {
        if (str === obj.name) {
          delete obj.address;
          delete obj.value;
          return obj;
        }
      }
      return false;
    },

    // 批量删除标签（所有选中的条目带有tag,都会删除掉）
    deleteTagInIds(tag_id, index) {
      var ids = this.getIds(tag_id);
      var data = { tag_id, ids };
      this.axios
        .post("/tagImage/deleteTags", data)
        .then(() => {
          this.newLabels.splice(index, 1); //更新tags
          this.loaddata(this.queryData);
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 获取已选择的ids(带有当前标签的)
    getIds(tag_id) {
      var ids = [];
      for (var a of this.selected) {
        for (var obj of a.label) {
          if (obj.id == tag_id) {
            ids.push(a.id);
          }
        }
      }
      return ids;
    },

    handleCloseAddTag() {
      this.visible = false;
    },

    // 删除标签
    handleClose(id, tag_id) {
      this.axios
        .post("/imagebase/deleteTag", { id, tag_id })
        .then(() => {
          this.loaddata(this.queryData);
          this.$message.success("已删除");
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },

    // 单个图片下架
    singleOff(val) {
      this.axios
        .get("/imagebase/singleOff", { params: { id: val } })
        .then(res => {
          if (res[0] > 0) {
            this.loaddata(this.queryData);
            this.$message.info("已下架");
          }
        })
        .catch(() => {
          this.$message.error("下架失败");
        });
    },

    // 单个图片上架
    singleUp(val) {
      this.axios
        .get("/imagebase/singleUp", { params: { id: val } })
        .then(res => {
          if (res[0] > 0) {
            this.loaddata(this.queryData);
            this.$message.success("已上架");
          }
        })
        .catch(() => {
          this.$message.error("上架失败");
        });
    },

    // 批量操作标签
    TagsInBatches() {
      this.selected = this.multipleSelection;
      var arr = this.selected;
      if (arr.length === 0) {
        this.$message.error("请选择需要操作的选项");
        return;
      }
      this.newLabels = this.makeTags(arr);
      this.dialogFormVisible = true;
    },

    makeTags(arr) {
      var labels = [];
      for (var a of arr) {
        for (var obj of a.label) {
          labels.push(obj);
        }
      }
      labels = this.unique01(labels);

      return labels;
    },

    // 批量添加标签
    addTags() {
      if (this.newTags.length < 1) {
        this.$message.error("请选择新标签！");
        return;
      }
      //图片ID数组
      var ids = this.selectedIds;
      //选中的图片数组
      let data = {};
      data.ids = ids;
      data.tags = this.newTags;
      this.axios.post("/tagImage/groupAddTags", data).then(res => {
        this.newLabels = this.newLabels.concat(res);
        this.newTags = []; //清空选项框
      });
    },
    closeAddTags() {
      this.dialogFormVisible = false;
      this.loaddata(this.queryData);
    },
    /**
     * @author: Shihh
     * @description: 数据构造
     * @param {type}
     * @return:
     */

    getTegIds(arr) {
      var a = [];
      for (var obj of arr) {
        a.push({ id: obj.id, name: obj.name });
      }
      return a;
    },

    // 批量操作上架下架
    bsatchOperation(command) {
      if (command == "shelves") {
        this.shelvesInBulk();
      } else if (command == "delisted") {
        this.delistedInBulk();
      } else if (command == "review") {
        this.review();
      } else if (command == "editCategory") {
        this.editCategory();
      } else if (command == "getImageIds") {
        this.getImageIds();
      }
    },
    // 批量上架
    shelvesInBulk() {
      var multipleSelection = this.multipleSelection;
      if (multipleSelection.length > 0) {
        var ids = [];
        for (const obj of multipleSelection) {
          ids.push(obj.id);
        }
        this.axios
          .post("/imagebase/imagesUp", { ids })
          .then(res => {
            if (res[0] > 0) {
              this.$message.success("成功上架" + res[0] + "张");
              this.loaddata(this.queryData);
            }
          })
          .catch(() => {
            this.$message.error("上架失败");
          });
      } else {
        this.$message.error("请选择需要上架的图片");
      }
    },
    // 批量下架
    delistedInBulk() {
      var multipleSelection = this.multipleSelection;
      if (multipleSelection.length > 0) {
        var ids = [];
        for (const obj of multipleSelection) {
          ids.push(obj.id);
        }
        this.axios
          .post("/imagebase/imagesDown", { ids })
          .then(res => {
            if (res[0] > 0) {
              this.$message.success("已经下架" + res[0] + "张");
              this.loaddata(this.queryData);
            }
          })
          .catch(() => {
            this.$message.error("操作失败");
          });
      } else {
        this.$message.error("请选择需要下架的图片");
      }
    },
    // 批量审核
    review() {
      console.log("review");
    },
    editBatchCategory() {
      if (this.batchCategoryForm.id.length) {
        var multipleSelection = this.multipleSelection;
        if (multipleSelection.length > 0) {
          var ids = [];
          for (const obj of multipleSelection) {
            ids.push(obj.id);
          }
          var target = this.batchCategoryForm.id;
          this.axios
            .post("/imagebase/batchCategory", {
              ids: ids,
              categoryId: target.pop()
            })
            .then(res => {
              if (res) {
                this.$message.success(res.msg);
                this.loaddata(this.queryData);
                this.categoryBatchForm = false;
              }
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
          this.$message.info("请选择图片");
        }
      } else {
        this.$message.info("请选择分类");
      }
    },
    // 批量修改分类
    async editCategory() {
      if (this.multipleSelection.length > 0) {
        var categorys = [];
        await this.axios
          .get("/category/category-list", {})
          .then(res => {
            if (res.code == 200) {
              categorys = res.rows;
            }
          })
          .catch(() => {
            this.$message.error("获取列表失败");
          });
        categorys.forEach(item => {
          var pushItem = { value: item.id, label: item.name };
          if (item.children) {
            pushItem.children = [];
            item.children.forEach(c_item => {
              pushItem.children.push({ value: c_item.id, label: c_item.name });
            });
          }
          this.categoryOptions.push(pushItem);
        });
        this.categoryBatchForm = true;
      } else {
        this.$message.error("请选择需要设置分类的图片");
      }
    },

    getImageIds() {
      if (this.multipleSelection.length > 0) {
        var imageIds = [];
        this.multipleSelection.forEach(item => {
          imageIds.push(item.id);
        });
        this.exportTxt("imageIds.txt", imageIds.toString());
      } else {
        this.$message.error("请选择图片");
      }
    },

    //下载表格
    downloadForm() {
      this.queryData.pageSet.page = 1;
      this.queryData.pageSet.pagesize = this.tableData.length;
      this.exportExcel(this.tableData, "#out-table");
    },

    loaddata(params) {
      this.axios
        .post("/imagebase/searchImg", params)
        .then(res => {
          this.total = res.count;
          for (let row of res.rows) {
            row.is_enable_Bool = row.is_enable == 0;
          }
          this.tableData = res.rows;
        })
        .catch(() => {
          this.$message.error("获取列表失败");
        });
    },

    getCategory() {
      this.axios.get("/category/category-list", {}).then(res => {
        this.categoryData = res.rows;
      });
    },

    handleCurrentChange(val) {
      this.queryData.pageSet.page = val;
      this.loaddata(this.queryData);
    },

    handleSizeChange(val) {
      this.queryData.pageSet.pagesize = val;
      this.loaddata(this.queryData);
    },

    resetFrom() {
      for (var key in this.queryData.searchData) {
        this.queryData.searchData[key] = "";
      }
      this.selectTag = "";
      this.selectCategory = "";
      this.queryData.pageSet.page = 1;
      this.loaddata(this.queryData);
    },

    onSubmit() {
      this.queryData.pageSet.page = 1;
      this.loaddata(this.queryData);
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.selectedIds = this.getSelectIds(val);
      // this.selectedLabels = this.makeTags(this.selected);
    },
    getSelectIds(val) {
      var ids = [];
      for (var obj of val) {
        ids.push(obj.id);
      }
      return ids;
    },

    querySearch(queryString, cb) {
      var tagList = this.tagList;
      var results = queryString
        ? tagList.filter(this.createFilter(queryString))
        : tagList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },

    // 获取标签
    loadTags() {
      this.axios
        .get("/tag/getTagsList", {})
        .then(res => {
          var rows = res;
          for (var obj of rows) {
            obj.address = obj.id;
            obj.value = obj.name;
          }
          this.tagList = rows;
        })
        .catch(() => {
          this.$message.error("获取标签列表失败");
        });
    },
    handleSelect(item) {
      this.lable = item;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-table td div {
  width: 100%;
}

.el-table .status {
  white-space: normal;
  text-align: center;
}

.el-table .cell {
  white-space: normal !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}
</style>